import 'dart:async';
import 'dart:io';
import 'dart:math';
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_red_num_widget/common_red_num_widget.dart';
import 'package:e_reception_flutter/constants/call_back.dart';
import 'package:e_reception_flutter/media_library/media_library_index/bean/video_upload_success_bean.dart';
import 'package:e_reception_flutter/media_library/media_library_index/service/media_library_index_service.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/mypage/mypage_attendance_ecord_widget/feedback_details_page.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_matisse_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_photo_preview/vg_photo_preview.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/vg_text_field.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:matisse_android_plugin/export_matisse.dart';
import 'package:path_provider/path_provider.dart';
import 'package:photo_preview/photo_preview_export.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_permission_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_time_util_lib.dart';
import 'package:video_thumbnail/video_thumbnail.dart';
import '../../app_main.dart';
import '../my_page_view_model.dart';
import 'detailed_bean/mypage_proposal_total_bean.dart';

class MyPageProposalImprovementWidget extends StatefulWidget {
  final AllAndUnReadCntNumber allAndUnReadCnt;

  const MyPageProposalImprovementWidget({Key key, this.allAndUnReadCnt})
      : super(key: key);

  ///跳转方法
  ///markedInfoBean 提前缓存加载（需要通用修改重构）
  static Future<dynamic> navigatorPush(
      BuildContext context, AllAndUnReadCntNumber allAndUnReadCnt) {
    return RouterUtils.routeForFutureResult(
      context,
      MyPageProposalImprovementWidget(allAndUnReadCnt: allAndUnReadCnt),
    );
  }

  @override
  _MyPageProposalImprovementWidgetState createState() =>
      _MyPageProposalImprovementWidgetState();
}

class _MyPageProposalImprovementWidgetState
    extends BaseState<MyPageProposalImprovementWidget> {
  TextEditingController _editingController;
  MyPageViewModel viewModel;

  bool isAlive = false;

  String editStr;

  List<String> resultList;

  List<String> adjustmentResultList;

  AllAndUnReadCntNumber allAndUnReadCnt;

  List<UploadMediaLibraryItemBean> _uploadList = List();

  var lastPopTime;

  @override
  void initState() {
    super.initState();
    viewModel = MyPageViewModel(this);
    resultList = List<String>();
    adjustmentResultList = List<String>();
    _editingController = TextEditingController();
    allAndUnReadCnt = widget?.allAndUnReadCnt;
    lastPopTime = DateTime.now().add(Duration(minutes: -1));
  }

  //限制3秒内只能点击一次
  bool intervalClick(int needTime) {
    // 防重复提交
    if (lastPopTime == null ||
        DateTime.now().difference(lastPopTime) > Duration(seconds: needTime)) {
      lastPopTime = DateTime.now();
      print("允许点击");
      return false;
    } else {
      // lastPopTime = DateTime.now(); //如果不注释这行,则强制用户一定要间隔2s后才能成功点击. 而不是以上一次点击成功的时间开始计算.
      print("请勿重复点击！");
      return true;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      resizeToAvoidBottomPadding: false,
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      body: _proposalImprovementWidget(),
    );
  }

  Widget _proposalImprovementWidget() {
    _aliveButton(); //判断提交按钮
    return Column(
      children: [
        _toTopBarWidget(),
        _proposalTextBox(),
        SizedBox(
          height: 30,
        ),
        _submitProposal(),
      ],
    );
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(title: "意见反馈", isShowBack: true);
  }

  Widget _proposalTextBox() {
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      child: SingleChildScrollView(
        physics: NeverScrollableScrollPhysics(),
        child: Column(
          children: [
            _toStatusBarWidget(),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 15),
              child: VgTextField(
                controller: _editingController,
                maxLines: 7,
                minLines: 7,
                maxLength: 200,
                autofocus: true,
                decoration: InputDecoration(
                  border: InputBorder.none,
                  counterText: "",
                  contentPadding: const EdgeInsets.only(top: 15),
                  hintText: "有问题，有建议，欢迎提交给我们",
                  hintStyle: TextStyle(
                      color: ThemeRepository.getInstance()
                          .getHintGreenColor_5E687C(),
                      fontSize: 14),
                ),
                style: TextStyle(
                    fontSize: 14,
                    color: ThemeRepository.getInstance()
                        .getTextMainColor_D0E0F7()),
                onChanged: (String str) {
                  editStr = str;
                  setState(() {});
                },
              ),
            ),
            Row(
              children: [
                Spacer(),
                Container(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 15, vertical: 15),
                  child: Row(
                    children: [
                      Text(
                        "${editStr?.length ?? 0}",
                        style: TextStyle(
                          fontSize: 10,
                          color: (editStr?.length ?? 0) > 0
                              ? ThemeRepository.getInstance()
                                  .getPrimaryColor_1890FF()
                              : ThemeRepository.getInstance()
                                  .getHintGreenColor_5E687C(),
                        ),
                      ),
                      Text(
                        "/200",
                        style: TextStyle(
                          fontSize: 10,
                          color: ThemeRepository.getInstance()
                              .getHintGreenColor_5E687C(),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            // if(false)
            Container(
              padding: const EdgeInsets.only(
                  bottom: 15, top: 10, left: 15, right: 15),
              alignment: Alignment.centerLeft,
              child: (adjustmentResultList?.length ?? 0) == 0
                  ? Container(
                      width: 84,
                      height: 84,
                      child: GestureDetector(
                          onTap: () async {
                            if (intervalClick(2) ?? false) {
                              return null;
                            }
                            setState(() {
                              _addPicVidFile();
                            });
                          },
                          child: Image.asset(
                              "images/binding_terminal_add_pic_ico.png")),
                    )
                  : _toTitleWidget(adjustmentResultList),
            )
          ],
        ),
      ),
    );
  }

  void _aliveButton() {
    if (adjustmentResultList?.length != 0 || (editStr?.length ?? 0) != 0) {
      if (adjustmentResultList?.length == 1 &&
          adjustmentResultList[0]?.contains("defaultPicture") &&
          (editStr?.length ?? 0) == 0) {
        isAlive = false;
      } else {
        isAlive = true;
      }
    } else {
      isAlive = false;
    }
  }

  void _addPicVidFile() async {
    resultList = await MatisseUtil.selectAll(
        maxImageSize: 9,
        maxVideoSize: 9,
        videoMemoryLimit: 500 * 1024,
        videoDurationLimit: 10 * 60,
        videoDurationMinLimit: 10,
        isCanMixSelect: true,
    onRequestPermission: (msg)async{
      bool result =
          await CommonConfirmCancelDialog.navigatorPushDialog(context,
        title: "提示",
        content: msg,
        cancelText: "取消",
        confirmText: "去授权",
      );
      if (result ?? false) {
        PermissionUtil.openAppSettings();
      }
    });
    if (resultList == null || resultList.isEmpty) {
      return;
    }
    resultList?.forEach((element) {
      if ((adjustmentResultList?.length ?? 0) < 10) {
        if (MatisseUtil.isVideo(element)) {
          handleVideo(element);
        } else if (MatisseUtil.isImage(element)) {
          chuLPicture(element);
        }
        adjustmentResultList?.add(element);
      } else {
        VgToastUtils.toast(context, "只能上传9张图片");
      }
    });
    setState(() {});
    // if((adjustmentResultList?.length??0)!=0){
    //   isAlive = true;
    // }
  }

  void chuLPicture(String clipPath) {
    if (StringUtils.isNotEmpty(clipPath)) {
      FileImage image = FileImage(File(clipPath));
      image
          .resolve(new ImageConfiguration())
          .addListener(new ImageStreamListener((ImageInfo info, bool _) async {
        _uploadList.add(UploadMediaLibraryItemBean(
            localUrl: clipPath,
            mediaType: MediaType.image,
            folderWidth: info.image.width,
            folderHeight: info.image.height));
      }));
    }
  }

  ///处理视频的逻辑
  void handleVideo(String localUrl) async {
    //视频
    UploadMediaLibraryItemBean item = UploadMediaLibraryItemBean(
      localUrl: localUrl,
      mediaType: MediaType.video,
    );

    File file = File(item.localUrl);
    Directory rootPath = await getTemporaryDirectory();
    Directory tempDirectory = new Directory('${rootPath.path}/imageTemp');
    if (!tempDirectory.existsSync()) {
      tempDirectory.createSync();
    }

    String tmpVideoCover = await VideoThumbnail.thumbnailFile(
      video: item.localUrl,
      thumbnailPath: tempDirectory?.path,
      imageFormat: ImageFormat.JPEG,
      maxWidth: 1920,
      quality: 100,
    );
    item.videoLocalCover = tmpVideoCover;
    //
    VideoPlayerController videoController = VideoPlayerController.file(file);
    await videoController.initialize();
    item.videoDuration = videoController?.value?.duration?.inSeconds;
    item.folderWidth = videoController?.value?.size?.width?.floor();
    item.folderHeight = videoController?.value?.size?.height?.floor();
    item.folderStorage = file.lengthSync();

    _uploadList.add(item);
    videoController.dispose();
    setState(() {});
  }

  ///图片展示栏
  Widget _toTitleWidget(List<String> data) {
    if (data?.length != 0 && (data?.length ?? 0) < 11) {
      List<String> Str = List<String>();
      data?.forEach((element) {
        Str?.add(element);
      });
      if ((Str?.toString()?.contains("defaultPicture"))) {
        data?.remove("defaultPicture");
      }
      if (data?.length < 9) {
        data?.insert(data?.length, "defaultPicture");
      }
    }
    return Container(
        child: GridView.builder(
            itemCount: data?.length ?? 0,
            padding: const EdgeInsets.all(0),
            physics: NeverScrollableScrollPhysics(),
            shrinkWrap: true,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 4,
              mainAxisSpacing: 5,
              crossAxisSpacing: 3,
            ),
            itemBuilder: (BuildContext context, int index) {
              if (data[index]?.contains("defaultPicture")) {
                return GestureDetector(
                  onTap: () async {
                    if (intervalClick(2) ?? false) {
                      return null;
                    }
                    setState(() {
                      _addPicVidFile();
                    });
                  },
                  child: Container(
                    width: 84,
                    height: 84,
                    child:
                        Image.asset("images/binding_terminal_add_pic_ico.png"),
                  ),
                );
              }
              return _toListItemWidget(context, data?.elementAt(index));
            }));
  }

  Widget _toStatusBarWidget() {
    return Visibility(
      visible: (allAndUnReadCnt?.allCnt ?? 0) != 0,
      child: GestureDetector(
        onTap: () {
            // RouterUtils.routeForFutureResult(context, NewFilePage());
          allAndUnReadCnt?.unreadCnt = 0;
          MyPageFeedBackDetailsWidget.navigatorPush(context);
          setState(() {});
        },
        child: Container(
          color: Color(0xFF188EFB).withOpacity(0.1),
          height: 40,
          child: Row(
            children: [
              SizedBox(
                width: 15,
              ),
              Text(
                "共${allAndUnReadCnt?.allCnt ?? 0}条意见反馈",
                style: TextStyle(
                  fontSize: 14,
                  color: Color(0xFF188EFB),
                ),
              ),
              Spacer(),
              CommonRedNumWidget(
                (allAndUnReadCnt?.unreadCnt ?? 0) ?? 0,
                isShowZero: false,
              ),
              SizedBox(
                width: 10,
              ),
              Icon(
                Icons.arrow_forward_ios,
                size: 14,
                color: VgColors.INPUT_BG_COLOR,
              ),
              SizedBox(
                width: 15,
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget _toListItemWidget(BuildContext context, String url) {
    int isUrl = 0;
    if (MatisseUtil.isVideo(url)) {
      for (int i = 0; i < _uploadList?.length; i++) {
        if (url?.contains("/") && url?.contains(".")) {
          if (_uploadList[i]?.getLocalPicUrl()?.contains(url?.substring(
              url?.lastIndexOf("/", url?.lastIndexOf("/")),
              url?.lastIndexOf(".", url?.lastIndexOf("."))))) {
            isUrl = i;
          }
        }
      }
    }
    return Stack(
      fit: StackFit.expand,
      children: [
        GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            VgPhotoPreview.single(
                AppMain.context, showOriginEmptyStr(url) ?? "");
          },
          child: ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: Container(
              width: 84,
              height: 84,
              child: VgCacheNetWorkImage(
                MatisseUtil.isVideo(url) && _uploadList?.length != 0
                    ? _uploadList[isUrl]?.getLocalPicUrl() ?? null
                    : url,
                imageQualityType: ImageQualityType.middleUp,
                emptyWidget: Center(
                  child: Container(
                    width: 35,
                    height: 35,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                    ),
                  ),
                ),
                errorWidget: Center(
                  child: Container(
                    width: 35,
                    height: 35,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                    ),
                  ),
                ),
              ),
            ),
          ),
        ),
        Positioned(
          top: 0,
          right: 0,
          child: GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              adjustmentResultList?.remove(url);
              setState(() {});
            },
            child: Padding(
              padding:
                  const EdgeInsets.only(left: 10, bottom: 10, top: 4, right: 4),
              child: Container(
                width: 15,
                height: 15,
                decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: ThemeRepository.getInstance()
                        .getBgOrSplitColor_191E31()
                        .withOpacity(0.5)),
                child: Icon(
                  Icons.close,
                  size: 11,
                  color:
                      ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  void upload(VgBaseCallback callback) async {
    if ((adjustmentResultList?.length ?? 0) == 0) {
      callback?.onError("需要上传的数据为空");
      return;
    }
    //处理上传数据
    List<UploadMediaLibraryItemBean> newUploadList = List();
    adjustmentResultList?.forEach((endElement) {
      _uploadList?.forEach((element) {
        if (endElement?.contains(element?.localUrl)) {
          newUploadList?.add(element);
        }
      });
    });
    _uploadList = newUploadList;
    VgHudUtils.show(context, "正在上传");
    print("打印需要上传的信息：$_uploadList");
    List<Future<UploadMediaLibraryItemBean>> futureList = List();
    for (UploadMediaLibraryItemBean item in _uploadList) {
      futureList.add(_httpFolder(item, onGetNewFileLength: (value) {
        item.folderStorage = value;
      }));
    }
    Future.wait(futureList)
      ..then((List<UploadMediaLibraryItemBean> list) {
        callback?.onSuccess(list);
      }).catchError((e) {
        callback?.onError("个别文件上传失败");
      });
  }

  Future<UploadMediaLibraryItemBean> _httpFolder(
      UploadMediaLibraryItemBean item,
      {ValueChanged<int> onGetNewFileLength}) async {
    if (item == null) {
      return null;
    }
    if (item.isImage()) {
      try {
        item.netUrl = await VgMatisseUploadUtils.uploadSingleImageForFuture(
            item.localUrl,
            isNoCompress: false,
            onGetNewFileLength: onGetNewFileLength);
        if (StringUtils.isEmpty(item.folderName)) {
          item.folderName = item?.getFolderNameStr() ?? "";
        }
        return item;
      } catch (e) {
        print("上传单图异常：$e");
      }
    }
    if (item.isVideo()) {
      try {
        VideoUploadSuccessBean successBean =
            await VgMatisseUploadUtils.uploadSingleVideoForFuture(
                item.localUrl);
        item.netUrl = successBean.url;
        item.videoid = successBean.videoid;
        item.folderName = VgMatisseUploadUtils.getVideoPath();
        if (!StringUtils.isEmpty(successBean.fileSize)) {
          item.folderStorage = int.parse(successBean.fileSize);
        }
        item.videoNetCover =
            await VgMatisseUploadUtils.uploadSingleImageForFuture(
                item.videoLocalCover,
                isNoCompress: false);
        return item;
      } catch (e) {
        print("MyPageProposalImprovementWidget上传异常：$e");
      }
    }
    return null;
  }

  Widget _submitProposal() {
    return Center(
      child: CommonFixedHeightConfirmButtonWidget(
        isAlive: isAlive,
        width: VgToolUtils.getScreenWidth(),
        height: 40,
        margin: const EdgeInsets.symmetric(horizontal: 15),
        unSelectBgColor: Color(0xFF3A3F50),
        selectedBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
        unSelectTextStyle: TextStyle(
          color: VgColors.INPUT_BG_COLOR,
          fontSize: 15,
        ),
        selectedTextStyle: TextStyle(
          color: Colors.white,
          fontSize: 15,
          // fontWeight: FontWeight.w600
        ),
        text: "提交",
        onTap: () {
          if (!isAlive) return VgToastUtils.toast(context, "请完善信息");
          VgToolUtils.removeAllFocus(context);
          if ((adjustmentResultList?.length ?? 0) > 1) {
            upload(VgBaseCallback(onSuccess: (val) {
              if (val?.length != 0) {
                _uploadList = val;
                List<String> picurlListUrl = List<String>();
                List<String> videoListUrl = List<String>();
                _uploadList?.forEach((element) {
                  if (MatisseUtil.isVideo(element?.netUrl)) {
                    videoListUrl?.add(element?.netUrl);
                  } else if (MatisseUtil.isImage(element?.netUrl)) {
                    picurlListUrl?.add(element?.netUrl);
                  }
                });
                viewModel?.submitProposalData(
                    context,
                    editStr,
                    VgStringUtils.getSplitStr(picurlListUrl, symbol: ","),
                    VgStringUtils.getSplitStr(videoListUrl, symbol: ","));
              }
              VgHudUtils.hide(context);
              VgHudUtils.hide(AppMain.context);
              VgToastUtils.toast(AppMain.context, "上传完成");
              RouterUtils.pop(context);
            }, onError: (msg) {
              VgHudUtils.hide(context);
              VgToastUtils.toast(AppMain.context, "上传失败");
              // RouterUtils.pop(context);
            }));
          } else {
            viewModel?.submitProposalData(context, editStr, "", "");
          }
        },
      ),
    );
  }
}
